/**
 * 
 */
//polling  시간 간격
var time_interval = 100; 

var id,yPos,xPos,avatarType;
var avatarObj;
var avatarTemplateHtml, avatarHtml;
var mainScreenObj;
var rankTableObj, rankInTdObj;
var objPollDivObj, objTitleObj, opt1Obj, opt2Obj, opt3Obj, opt4Obj, optPoint1Obj, optPoint2Obj, optPoint3Obj, optPoint4Obj;
var subPollDivObj, subTitleObj;
var oxPollDivObj, oxTitleObj, oxOpt1Obj, oxOpt2Obj, oxOptPoint1Obj, oxOptPoint2Obj;
var PtContentsDivObj, hiddenPollIdObj, hiddenQstTypeCdObj, rankObj, youtubeObj, preziObj, practiceObj;
var scoreTableObj, scoreLabelObj;
var tempBalloonObj;
var practiceMessageObj, lastResultRankObj, practiceTableObj, lastResultRankTableObj;
var scoreCountingYn;
var cnt = 0;

$(window.document).ready(function(){
	avatarTemplateHtml = $("#hiddenDiv").html();
	avatarHtml = "";
	mainScreenObj = $("#mainScreen");
	rankTableObj = $("#rankTable");
	rankInTdObj = $("#rankInTd");
	objPollDivObj = $("#objPollDiv");
	objTitleObj = $("#objTitle");
	opt1Obj = $("#opt1");
	opt2Obj = $("#opt2");
	opt3Obj = $("#opt3");
	opt4Obj = $("#opt4");
	optPoint1Obj = $("#optPoint1");
	optPoint2Obj = $("#optPoint2");
	optPoint3Obj = $("#optPoint3");
	optPoint4Obj = $("#optPoint4");
	subPollDivObj = $("#subPollDiv");
	subTitleObj = $("#subTitle");
	oxPollDivObj = $("#oxPollDiv");
	oxTitleObj = $("#oxTitle");
	oxOpt1Obj = $("#oxOpt1");
	oxOpt2Obj = $("#oxOpt2");
	oxOptPoint1Obj = $("#oxOptPoint1");
	oxOptPoint2Obj = $("#oxOptPoint2");
	PtContentsDivObj = $("#PtContentsDiv");
	hiddenPollIdObj = $("#hiddenPollId");
	hiddenQstTypeCdObj = $("#hiddenQstTypeCd");
	rankObj = $("#rank");
	youtubeObj = $("#youtubeDiv");
	preziObj = $("#preziDiv");
	pollMainTableObj = $("#pollMainTable");
	practiceObj = $("#practiceDiv");
	scoreTableObj = $("#scoreTable");
	scoreLabelObj = $("#scoreLabel");
	practiceMessageObj = $("#practiceMessage");
	lastResultRankObj = $("#lastResultRank");
	practiceTableObj = $("#practiceTable");
	lastResultRankTableObj = $("#lastResultRankTable");
	initScreen();
	getAllAvatar();

	//polling 방식
	setInterval(function(){
		getAllAvatar();
	}, time_interval);
	
	/* 
	 * stop Interval sample
	 * var refreshIntervalId = setInterval(fname, 10000);
	 * clearInterval(refreshIntervalId);
	 * 
	 * */
	//initFlip();
	//setTimeout(function(){setTutorialMode();}, 20);
});

//초기화
function initScreen(){
	//	설문 숨김
	objPollDivObj.hide();
	subPollDivObj.hide();
	// 말풍선 숨김
	hideBalloon();
	setPtMode();
	setPosition(true);
}

/** 좌표 범위 설정 */
function setPosition(isSub) {
	var objTitleHeight = 0;
	var baloonHeight = 40;
	if( !isSub ) {
		objTitleHeight = 110;
		baloonHeight = 0;
	}
	var pollMainObj = $("#pollMainTd");
	var minPosX = pollMainObj.position().left + 10;
	var minPosY = pollMainObj.position().top + objTitleHeight; //객관식 제목 크기
	var maxPosX = pollMainObj.width() - 40;
	var maxPosY = pollMainObj.height() - 60 - baloonHeight;
//	var minPosX = 0;
//	var minPosY = 100;
//	var maxPosX = 974;
//	var maxPosY = 718;
	$.ajax({
		type: "post",
		url: "setPositionAjax.json",
		data: "minPosX="+minPosX+"&minPosY="+minPosY+"&maxPosX="+maxPosX+"&maxPosY="+maxPosY,
		dataType: "json",
		async: false,
		success: function(data) { },
		error: function(data, status, error) {
			alert("데이터 전송에 실패하였습니다.\n\n[" + status + "] " + error);
		}
	});
}

/*
function initFlip(){
	var $container 	= $( '#flip' ),
	$pages		= $container.children().hide();

	Modernizr.load({
		test: Modernizr.csstransforms3d && Modernizr.csstransitions,
		yep : ['js/jquery.tmpl.min.js','js/jquery.history.js','js/core.string.js','js/jquery.touchSwipe-1.2.5.js','js/jquery.flips.js'],
		nope: 'css/fallback.css',
		callback : function( url, result, key ) {
			
			if( url === 'css/fallback.css' ) {
				$pages.show();
			}
			else if( url === 'js/jquery.flips.js' ) {
				$container.flips();
			}
	
		}
	});
}
*/

function getAllAvatar(){
	var url = "screenAjax.json";
	$.ajax({
		type: 		"POST"
		,url: 		url
		,dataType:	"json"
		,async:		false
		,success: 	function(data){
						if(data.ptStatCd != '26') cnt=0;
						switch(data.ptStatCd){
							case "10" : showRank(data, "left"); setAvatarMode(data); break;
							case "20" : setPtMode(data); break;
							case "25" : setYoutubeMode(data); break;
							case "26" : setPreziMode(data);cnt++; break;
							case "30" : showRank(data, "left"); setPollMode(data); break;
							case "40" : showRank(data, "left"); setCountingScoreMode(data); break;
							case "50" : practiceMode(data); break;
							default : break;
						}
					}
		,error: 	function(){ }
	});	
}
//하트 출력
function setTutorialMode(data) {

	for ( var i = 0; i < 15; i++) {

		var top = Math.ceil(Math.random() * (screen.availHeight - 250));
		var left = Math.ceil(Math.random() * (screen.availWidth - 200));
		var size = Math.ceil(Math.random() * 100);

		var img_height = $("#heart_img_" + i).height();
		var img_width = $("#heart_img_" + i).width();

		$("#heart_img_" + i).width(img_width - size + "px");
		$("#heart_img_" + i).height(img_height - size + "px");

		$("#heart_" + i).css({
			position : "absolute",
			top : top + "px",
			left : left + "px"
		});
	}
}

//아바타 이동하기
function moveAvatars(data){
	var id,yPos,xPos,avatarType;
	showAvatar();
	if(data.avatarVOList!=null){
		for(var i=0;i<data.avatarVOList.length;i++){
			id = data.avatarVOList[i].avatarId;
			yPos = data.avatarVOList[i].posY;
			xPos = data.avatarVOList[i].posX;
			avatarType = data.avatarVOList[i].avatarType;
			if(id!=null && id!=""){
				moveTo(id,yPos,xPos,avatarType);
			}
		}
		data.avatarVOList=null;
    }
}

//아바타 이동 모드
function setAvatarMode(data){
	hideAll();
	moveAvatars(data);
}

//프리젠테이션 진행 모드 ( 아바타 숨김 )
function setPtMode(){
	hideAll();
	PtContentsDivObj.show();
}

//youtube 모드
function setYoutubeMode(){
	hideAll();
	youtubeObj.show();
}

//prezi 모드
function setPreziMode(){
	if(cnt == 0){
		hideAll();
		preziObj.show();
	}
}

//모두 숨기기
function hideAll(){
	rankTableObj.hide();
	rankInTdObj.hide();
	subPollDivObj.hide();
	objPollDivObj.hide();
	oxPollDivObj.hide();
	PtContentsDivObj.hide();
	youtubeObj.hide();
	preziObj.hide();
	hideBalloon();
	hideAvatar();
	pollMainTableObj.hide();
	practiceObj.hide();
}

//설문 모드
function setPollMode(data){
	scoreCountingYn = "N";	//점수계산 FLAG 설정
	hideAll();
	moveAvatars(data);		//아바타 이동
	pollMainTableObj.show();
	if(data!=null && data.pollInfVO!=null){
		hiddenPollIdObj.val(data.pollInfVO.pollId);
		hiddenQstTypeCdObj.val(data.pollInfVO.qstTypeCd);
		if(data.pollInfVO.qstTypeCd =="OBJ"){
			//제목, 보기, 배점 (4개)
			objTitleObj.text(data.pollInfVO.qstVal);
			opt1Obj.html(data.pollInfVO.opt1);
			opt2Obj.html(data.pollInfVO.opt2);
			opt3Obj.html(data.pollInfVO.opt3);
			opt4Obj.html(data.pollInfVO.opt4);
			var optPoint1 = data.pollInfVO.optPoint1;
			var optPoint2 = data.pollInfVO.optPoint2;
			var optPoint3 = data.pollInfVO.optPoint3;
			var optPoint4 = data.pollInfVO.optPoint4;
			optPoint1Obj.val(optPoint1);
			optPoint2Obj.val(optPoint2);
			optPoint3Obj.val(optPoint3);
			optPoint4Obj.val(optPoint4);
			var maxPoint = optPoint1;
			if( maxPoint < optPoint2 ) maxPoint = optPoint2;
			if( maxPoint < optPoint3 ) maxPoint = optPoint3;
			if( maxPoint < optPoint4 ) maxPoint = optPoint4;
			scoreLabelObj.text(maxPoint);

			subPollDivObj.hide();
			oxPollDivObj.hide();
			objPollDivObj.show();
			rankTableObj.show();
			rankInTdObj.show();
			setPosition(false);
			scoreTableObj.show();
			hideBalloon();	//말풍선 숨기기

		}else if(data.pollInfVO.qstTypeCd =="SUB"){
			//제목
			subTitleObj.text(data.pollInfVO.qstVal);

			objPollDivObj.hide();
			oxPollDivObj.hide();
			subPollDivObj.show();
			rankTableObj.show();
			rankInTdObj.show();
			setPosition(true);
			scoreTableObj.hide();

			// 대답한 아바타 말풍선 띄워주기
			if(data.pollAswInfVOList!=null){
				var id,aswVal;
				for(var i=0;i<data.pollAswInfVOList.length;i++){
					id = data.pollAswInfVOList[i].avatarId;
					aswVal = data.pollAswInfVOList[i].aswVal;
					showBalloon(id,aswVal);
				}
				data.avatarVOList=null;
		    }
			
		}else if(data.pollInfVO.qstTypeCd =="OX"){
			//제목, 보기, 배점 (2개)
			oxTitleObj.text(data.pollInfVO.qstVal);
			oxOpt1Obj.html(data.pollInfVO.opt1);
			oxOpt2Obj.html(data.pollInfVO.opt2);
			var optPoint1 = data.pollInfVO.optPoint1;
			var optPoint2 = data.pollInfVO.optPoint2;
			oxOptPoint1Obj.val(optPoint1);
			oxOptPoint2Obj.val(optPoint2);
			var maxPoint = (optPoint1<optPoint2)? optPoint2:optPoint1;
			scoreLabelObj.text(maxPoint);

			objPollDivObj.hide();
			subPollDivObj.hide();
			oxPollDivObj.show();
			rankTableObj.show();
			rankInTdObj.show();
			setPosition(false);
			scoreTableObj.show();
			hideBalloon();	//말풍선 숨기기
		}
	}else{
		return false;
	}
}

function practiceMode(data){
	hideAll();
	var message = data.ptInfVO.message;
	if( message == "최종 순위 발표" ) {
		showRank(data, "center");
		practiceTableObj.hide();
		lastResultRankTableObj.show();
	}
	else {
		practiceMessageObj.html(message);
		lastResultRankTableObj.hide();
		practiceTableObj.show();
	}
	practiceObj.show();

	//subTitleObj.text(data.pollInfVO.qstVal);
	//subPollDivObj.show();
}

//점수 계산 모드
function setCountingScoreMode(data){
	PtContentsDivObj.hide();
	qstTypeCd = hiddenQstTypeCdObj.val();
	if(scoreCountingYn=='N'){
		if( qstTypeCd == "OBJ" ) {
			scoreCountingYn="Y"; //1번만 점수 계산 해주기 위함.
			//아바타 점수 말풍선 달아주기
			var opt1MinX = getMinXByObject(opt1Obj);
			var opt1MaxX = getMaxXByObject(opt1Obj);
			var opt1MinY = getMinYByObject(opt1Obj);
			var opt1MaxY = getMaxYByObject(opt1Obj);
			var opt2MinX = getMinXByObject(opt2Obj);
			var opt2MaxX = getMaxXByObject(opt2Obj);
			var opt2MinY = getMinYByObject(opt2Obj);
			var opt2MaxY = getMaxYByObject(opt2Obj);
			var opt3MinX = getMinXByObject(opt3Obj);
			var opt3MaxX = getMaxXByObject(opt3Obj);
			var opt3MinY = getMinYByObject(opt3Obj);
			var opt3MaxY = getMaxYByObject(opt3Obj);
			var opt4MinX = getMinXByObject(opt4Obj);
			var opt4MaxX = getMaxXByObject(opt4Obj);
			var opt4MinY = getMinYByObject(opt4Obj);
			var opt4MaxY = getMaxYByObject(opt4Obj);
			var optPoint1 = optPoint1Obj.val();
			var optPoint2 = optPoint2Obj.val();
			var optPoint3 = optPoint3Obj.val();
			var optPoint4 = optPoint4Obj.val();
			var avatarId, offset, left, top, avatarX, avatarY, point;
			var avatarMap = {};
			mainScreenObj.children("div[id^='avatar_']").each(function(){
				avatarId = $(this).children("input:hidden[id^='hiddenAvatarId_']").val();
				offset = $(this).offset();
				left = offset.left;
				top = offset.top;
				avatarX = (left+left+$(this).width())/2;
				avatarY = (top+top+$(this).height())/2;
				point = 0;

				if( avatarX>opt1MinX && avatarX<opt1MaxX && avatarY>opt1MinY && avatarY<opt1MaxY ) point = optPoint1;
				else if( avatarX>opt2MinX && avatarX<opt2MaxX && avatarY>opt2MinY && avatarY<opt2MaxY ) point = optPoint2;
				else if( avatarX>opt3MinX && avatarX<opt3MaxX && avatarY>opt3MinY && avatarY<opt3MaxY ) point = optPoint3;
				else if( avatarX>opt4MinX && avatarX<opt4MaxX && avatarY>opt4MinY && avatarY<opt4MaxY ) point = optPoint4;

				if( point > 0 ) showBalloon(avatarId,"+"+point);
//				$(this).children().eq(1).show();
//				$(this).children().eq(1).text("+" + point);

//				$(this).find("div[id^=balloon_]").show();
//				$(this).find("div[id^=balloon_]").text("+" + point);
				avatarMap[avatarId] = point;
			});
			var avatarMapJSONString = JSON.stringify(avatarMap);

			//아바타 점수 서버로 전달 및 순위 갱신
			$.ajax({
				type: "POST",
				url: "setScoreAjax.json",
				dataType: "json",
				data: "avatarMapJSONString="+avatarMapJSONString+"&pollId="+hiddenPollIdObj.val(),
				async: false,
				success: function(data){ },
				error: function(data, status, error){
					alert("점수 계산 실패\n데이터 전송에 실패하였습니다.\n\n[" + status + "] " + error);
				}
			});
		}
		else if( qstTypeCd == "OX" ) {
			scoreCountingYn="Y"; //1번만 점수 계산 해주기 위함.
			var oMinX = getMinXByObject(oxOpt1Obj);
			var oMaxX = getMaxXByObject(oxOpt1Obj);
			var oMinY = getMinYByObject(oxOpt1Obj);
			var oMaxY = getMaxYByObject(oxOpt1Obj);
			var xMinX = getMinXByObject(oxOpt2Obj);
			var xMaxX = getMaxXByObject(oxOpt2Obj);
			var xMinY = getMinYByObject(oxOpt2Obj);
			var xMaxY = getMaxYByObject(oxOpt2Obj);
			var oxOptPoint1 = oxOptPoint1Obj.val();
			var oxOptPoint2 = oxOptPoint2Obj.val();
			var avatarId, offset, left, top, avatarX, avatarY, point;
			var avatarMap = {};
			mainScreenObj.children("div[id^='avatar_']").each(function(){
				avatarId = $(this).children("input:hidden[id^='hiddenAvatarId_']").val();
				offset = $(this).offset();
				left = offset.left;
				top = offset.top;
				avatarX = (left+left+$(this).width())/2;
				avatarY = (top+top+$(this).height())/2;
				point = 0;

				if( avatarX>oMinX && avatarX<oMaxX && avatarY>oMinY && avatarY<oMaxY ) point = oxOptPoint1;
				else if( avatarX>xMinX && avatarX<xMaxX && avatarY>xMinY && avatarY<xMaxY ) point = oxOptPoint2;

				if( point > 0 ) showBalloon(avatarId,"+"+point); 
//				$(this).find("div[id^=balloon_]").text("+" + point);
				avatarMap[avatarId] = point;
			});
			var avatarMapJSONString = JSON.stringify(avatarMap);

			//아바타 점수 서버로 전달 및 순위 갱신
			$.ajax({
				type: "POST",
				url: "setScoreAjax.json",
				dataType: "json",
				data: "avatarMapJSONString="+avatarMapJSONString+"&pollId="+hiddenPollIdObj.val(),
				async: false,
				success: 	function(data){ },
				error: 		function(){ }
			});
		}
	}
}

//말풍선 보이기
function showBalloon(id,msg){
	tempBalloonObj = mainScreenObj.children("div[id='avatar_"+id+"']").children("div[id='balloon_"+id+"']");
	if( msg.length > 10 ) tempBalloonObj.css("padding-top","3px");
	else tempBalloonObj.css("padding-top","10px");
	tempBalloonObj.html(msg).show();
}

//말풍선 숨기기
function hideBalloon(id){
	if(id==null){
		mainScreenObj.find("div[id^='balloon_']").hide();
	}else{
		mainScreenObj.find("div[id='balloon_"+id+"']").hide();
	}
}

//아바타 숨기기
function hideAvatar(id){
	if(id==null){
		mainScreenObj.children("div[id^='avatar_']").hide();
	}else{
		mainScreenObj.children("div[id='avatar_"+id+"']").hide();
	}
}

//아바타 보이기
function showAvatar(id){
	if(id==null){
		mainScreenObj.children("div[id^='avatar_']").show();
	}else{
		mainScreenObj.children("div[id='avatar_"+id+"']").show();
	}
}
	
// 참고 : 1명당 2m 걸림
function moveTo(id,top,left,avatarType){
	avatarObj = mainScreenObj.children("div[id='avatar_"+id+"']");
	if(avatarObj.length == 0) {
		mainScreenObj.append(avatarTemplateHtml.replace(/#ID#/g,id));
		avatarObj = mainScreenObj.children("div[id='avatar_"+id+"']");
	}
	avatarObj.children("img").attr("src",getImgSrc(avatarType));

	//애니메이션 없이 이동
	avatarObj.css("top", top+"px");
	avatarObj.css("left", left+"px");

	//애니메이션 이동 - 자바스크립트 프로그램 시간이 오래 걸려 구현 안함.
	//avatarObj.animate({"top":top+"px","left":left+"px"},time_interval);
}

function showRank(data, position) {
	avatarVOList = data.avatarVOList;
	if( avatarVOList == null ) return null;
	if( position == "left" ) {
		rankObj.children().remove();
		var i, avatarVO;
		var html = "";
		for(i=0; i<avatarVOList.length; i++) {
			avatarVO = avatarVOList[i];
			if( i < 10 ) html += "<tr><td class='rankBody'><span class='rankNum'>"+(i+1)+"</span> <span class='rankUsrNm'>"+avatarVO.avatarId+"</span> <span class='rankScore' style='text-align:right; float:right; padding-right:10px;'>"+avatarVO.avatarScore+"</span></td></tr>";
			else break;
		}
		rankObj.append(html);
	}
	else if( position = "center" ) {
		lastResultRankObj.children().remove();
		var i, avatarVO;
		var html = "";
		for(i=0; i<avatarVOList.length; i++) {
			avatarVO = avatarVOList[i];
			if ( i<5 && avatarVO.avatarScore>0 ) html += "<tr><td></td><td class='rankBody' style='background-size:100% 50px;'><span class='rankNum'>"+(i+1)+"</span> <span class='rankUsrNm'>"+avatarVO.avatarId+"</span> <span class='rankScore' style='text-align:right; float:right; padding-right:20px;'>"+avatarVO.avatarScore+"</span></td><td></td></tr>";
			else break;
		}
		lastResultRankObj.append(html);
	}
}